package com.sunseagear.wind.common.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.router.SaRouterStaff;
import cn.dev33.satoken.stp.StpUtil;
import com.sunseagear.common.utils.SpringContextHolder;
import com.sunseagear.wind.common.helper.SysConfigHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 权限安全配置
 */

@Slf4j
@AutoConfiguration
@RequiredArgsConstructor
public class SecurityConfig implements WebMvcConfigurer {


    /**
     * 注册sa-token的拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        final String context = SpringContextHolder.getApplicationContext().getApplicationName();
        // 注册路由拦截器，自定义验证规则
        registry.addInterceptor(new SaInterceptor(handler -> {
            // 登录验证 -- 排除多个路径
            SaRouterStaff saRouterStaff = SaRouter.match(context + "/**")
                    .notMatch(context + "/sso/oauth2/**", context + "/static/**", context + "/resources/**");
            if (Boolean.parseBoolean(SysConfigHelper.getInstance().getSysConfig("openAPI").getValue())) {
                // 放行接口目录
                saRouterStaff.notMatch(context + "/json/oss/**", context + "/json/**");
            }
            saRouterStaff.check(r -> StpUtil.checkLogin());
        })).addPathPatterns("/**");
    }

}
